import 'package:flutter/material.dart';
import 'package:schoollifedemo/base/url_contract.dart';
import 'package:schoollifedemo/business/personal/viewmodel/personal_icon_select_page_viewmodel.dart';
import 'package:schoollifedemo/commonwidget/button_widget.dart';
import 'package:schoollifedemo/commonwidget/circle_empty_widget.dart';
import 'package:schoollifedemo/commonwidget/common_base_page.dart';
import 'package:schoollifedemo/commonwidget/common_dialog.dart';
import 'package:schoollifedemo/commonwidget/error_widget.dart';
import 'package:schoollifedemo/commonwidget/loading_widget.dart';
import 'package:schoollifedemo/commonwidget/text_widget_with_overflow.dart';
import 'package:schoollifedemo/entity/Entity.dart';

class PersonalIconSelectPage extends BaseStatefulPage {
  const PersonalIconSelectPage({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _PersonalIconSelectPageState();
  }
}

class _PersonalIconSelectPageState
    extends BasePageState<PersonalIconSelectPage> {
  final PersonalIconSelectPageViewModel _viewModel =
      PersonalIconSelectPageViewModel();
  String _defaultUrl = '';
  int _selectIndex = 0;

  @override
  void initState() {
    _viewModel.init();
    _viewModel.pullIconsList(
      onSuccess: () {
        _defaultUrl = _viewModel.photoListResp?.list?.first?.iconSrc ?? '';
        _viewModel.photoListResp?.list?.first?.photoColor =
            _viewModel.selectColor;
      },
      onFailure: (msg) {
        DialogUtils.showTitleAndMessageDialog(
          context,
          clickOutSideDismiss: true,
          title: '错误',
          msg: msg,
        );
      },
    );
    super.initState();
  }

  @override
  void dispose() {
    _viewModel.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return StreamBuilder(
      initialData: CommonLoadingState.loading,
      stream: _viewModel.loadingState,
      builder: (buildContext, snapshot) {
        final state = snapshot.data as CommonLoadingState?;
        switch (state) {
          case CommonLoadingState.loading:
            return _loadingWidget();
          case CommonLoadingState.successTypeOne:
          case CommonLoadingState.successTypeTwo:
            return _bodyWidget();
          default:
            return _errorWidget();
        }
      },
    );
  }

  Widget _bodyWidget() {
    return Scaffold(
      body: Container(
        color: Colors.white,
        child: RefreshIndicator(
          onRefresh: () async {
            // 刷新头像
            _viewModel.pullIconsList(
              onFailure: (msg) {
                DialogUtils.showTitleAndMessageDialog(
                  context,
                  clickOutSideDismiss: true,
                  title: '错误',
                  msg: msg,
                );
              },
            );
          },
          child: ListView(
            physics: const BouncingScrollPhysics(),
            children: [
              const Padding(
                padding: EdgeInsets.only(top: 10),
                child: TextWidgetWithOverflow(
                  '更改头像信息',
                  textAlign: TextAlign.left,
                  insideColor: Colors.transparent,
                  paddingLeft: 25,
                  fontSize: 28,
                ),
              ),
              Container(
                margin: const EdgeInsets.only(left: 10, right: 10, top: 20),
                child: CircleEmptyWidget(
                  Container(
                    margin: const EdgeInsets.only(top: 10, bottom: 10),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Center(
                          child: SizedBox(
                            width: 100,
                            height: 100,
                            child: ClipOval(
                              child:
                                  Image.network(_getIconAddress(_defaultUrl)),
                            ),
                          ),
                        ),
                        Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            ButtonWidget(
                              insideWidget: const TextWidgetWithOverflow(
                                '确定',
                                fontSize: 14,
                                insideColor: Colors.transparent,
                                textColor: Colors.white,
                              ),
                              enableColor: const Color(0xFF4CB830),
                              onButtonClick: () async {
                                bool? trueOrFalse = await DialogUtils
                                    .showCancelAndConfirmDialog(
                                  context,
                                  title: '提示',
                                  msg: '确定更改?',
                                );
                                if (trueOrFalse == true) {
                                  String? iconId = _viewModel.photoListResp
                                      ?.list?[_selectIndex]?.iconId;
                                  if (iconId?.isNotEmpty == true) {
                                    _viewModel.changeIcon(iconId!);
                                  }
                                  _viewModel.backToPage(context);
                                }
                              },
                            ),
                            ButtonWidget(
                              insideWidget: const TextWidgetWithOverflow(
                                '取消',
                                fontSize: 14,
                                insideColor: Colors.transparent,
                                textColor: Colors.white,
                              ),
                              enableColor: const Color(0xFFE85252),
                              onButtonClick: () {
                                _viewModel.backToPage(context);
                              },
                            ),
                          ],
                        ),
                      ],
                    ),
                  ),
                  width: double.infinity,
                ),
              ),
              Padding(
                padding: const EdgeInsets.only(
                    left: 10, right: 10, top: 20, bottom: 20),
                child: SizedBox(
                  height: double.maxFinite,
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Expanded(
                        child: GridView.builder(
                          itemCount:
                              _viewModel.photoListResp?.list?.length ?? 0,
                          itemBuilder: (buildContext, index) {
                            String? photoUrl =
                                _viewModel.photoListResp?.list?[index]?.iconSrc;
                            Color? photoColor = _viewModel
                                .photoListResp?.list?[index]?.photoColor;
                            return GestureDetector(
                              onTap: () async {
                                _selectIndex = index;
                                _viewModel.resetColor();
                                _viewModel.photoListResp?.list?[index]
                                    ?.photoColor = _viewModel.selectColor;
                                _defaultUrl = _viewModel
                                        .photoListResp?.list?[index]?.iconSrc ??
                                    '';
                                setState(() {});
                              },
                              child: Center(
                                child: Container(
                                  color: photoColor,
                                  width: 90,
                                  height: 90,
                                  child: ClipOval(
                                    child: Image.network(
                                      _getIconAddress(
                                        photoUrl ?? '',
                                      ),
                                    ),
                                  ),
                                ),
                              ),
                            );
                          },
                          gridDelegate:
                              const SliverGridDelegateWithFixedCrossAxisCount(
                            crossAxisCount: 3,
                            crossAxisSpacing: 5,
                            mainAxisSpacing: 5,
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  String _getIconAddress(String iconStr) {
    return UrlContract.baseAddress + '/' + iconStr;
  }

  Widget _loadingWidget() {
    return Scaffold(
      body: Container(
        color: Colors.white,
        child: const LoadingWidget(),
      ),
    );
  }

  Widget _errorWidget() {
    return Scaffold(
      body: Container(
        color: Colors.white,
        child: CommonErrorWidget(
          '错误重试',
          onButtonClick: () async {
            _viewModel.pullIconsList(
              onFailure: (msg) {
                DialogUtils.showTitleAndMessageDialog(
                  context,
                  clickOutSideDismiss: true,
                  title: '错误',
                  msg: msg,
                );
              },
            );
          },
        ),
      ),
    );
  }
}
